<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    button.backtop {
      position: fixed;
      right: 100px;
      bottom: 100px;
    }
    button.a {
      position: fixed;
      left: 100px;
      top: 100px;
    }
  </style>
</head>

<body style="height: 3000px">
  <div id="app">
    <button class="a" @click="isShow=!isShow">{{isShow?'隐藏':'显示'}}</button>
    <button class="backtop" v-if="isShow" v-backtop="200">回到顶部</button>
  </div>
  <script src="./vue.js"></script>
  <script>
    // 定义全局指令
    Vue.directive('backtop', {
      inserted(el, binding) {
        console.log(binding);
        /* 
          初始化隐藏
          滚动条滚动大于给定举例时，按钮显示，小于按钮隐藏
          点击按钮 回到顶部
         */
        el.style.display = "none";
        window.onscroll = () => {
          //  获取滚动举例
          const sTop = document.documentElement.scrollTop || document.body.scrollTop;
          // 显示按钮的滚动举例
          const sValue = binding.value || 200;
          console.log(111);
          if (sTop > sValue) {
            // 按钮显示
            el.style.display = "block";
          } else {
            el.style.display = "none";
          }
        }
        el.onclick = () => {
          window.scrollTo(0, 0);
        }
      },
      unbind(){
        console.log('指令所占标签停止使用了');
        window.onscroll = null;
      }
    })
    const vm = new Vue({
      el: '#app',
      data: {
        isShow: true
      }
    })
  </script>
</body>

</html>